/*
 * @Copyright: Copyright (c) 2030 吴周海
 * @Author: wzh200x@126.com
 * @Date: 2025-10-10 11:35:00
 * @LastEditors: wzh200x@126.com
 * @LastEditTime: 2025-10-21 15:17:09
 * @FilePath: \gogamewebserver\goGameWebServer\internal\model\entity\gameConfigModel.go
 * @Description: GameConfig 实体模型
 */
package entity

import (
	"context"

	"goGameWebServer/internal/common/logger"
	"goGameWebServer/internal/defines/cerror"
	"goGameWebServer/internal/defines/dataType"
	"goGameWebServer/internal/interfaces"
	"goGameWebServer/internal/manager/databasemanager"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gmeta"
)

type GameConfigModelData struct {
	gmeta.Meta `orm:"table: game_config"`
	Id         dataType.TypeDataBaseId `orm:"id"`       // 主键
	Name       string                  `orm:"name"`     // 名称(key)
	Type       int                     `orm:"type"`     // 类型 0-数值 1-文本
	ParentId   dataType.TypeDataBaseId `orm:"parentId"` // 父级配置ID
	Value      string                  `orm:"value"`    // 值
	IsActive   int                     `orm:"isActive"` // 是否生效 0-无效 1-有效
	Platform   int                     `orm:"platform"` // 平台
}

func (d *GameConfigModelData) Reset() {
	d.Id = 0
	d.Name = ""
	d.Type = 0
	d.ParentId = 0
	d.Value = ""
	d.IsActive = 0
	d.Platform = 0
}

type GameConfigModel struct {
	EntityModel
}

func (m *GameConfigModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := m.EntityData.(*GameConfigModelData); ok {
		one, err := base.GetDb().Model(m.Template).Where("id", entityData.Id).One()
		if err != nil {
			return err
		}
		if one == nil {
			return m.Create()
		}
		_ = one.Struct(m.EntityData)
		m.SetEntityDBID(entityData.Id)
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "game_config model data is invalid")
}

func (m *GameConfigModel) Create() error {
	if _, ok := m.EntityData.(*GameConfigModelData); ok {
		err := m.CreateDataToDB()
		if err != nil {
			return err
		}
		m.EntityData.(*GameConfigModelData).Id = m.EntityDBID
		logger.LoggerIns().Debug("create game_config success")
		return nil
	}
	return gerror.NewCodef(gcode.New(cerror.ERROR_ENTITY_PROPERTY_INVALID, "", nil), "game_config model create fail, data is invalid")
}

func NewGameConfigModel(name string) interfaces.IEntityModel {
	m := &GameConfigModel{
		EntityModel: NewEntityModel(name),
	}
	m.SetEntityData(&GameConfigModelData{
		Id:       0,
		Name:     "",
		Type:     0,
		ParentId: 0,
		Value:    "",
		IsActive: 0,
		Platform: 0,
	})
	m.SetTemplate(m.EntityData)
	return m
}

// GameConfigWithChildren 返回结构：内嵌 GameConfigModelData，并包含 Children
type GameConfigWithChildren struct {
	GameConfigModelData
	Children []GameConfigWithChildren `json:"children,omitempty"`
}

// buildPlatformCondition: platform==999 → platform >= 0；否则 → IN(platform, 0)
func buildPlatformCondition(platform int) g.Map {
	if platform == 999 {
		return g.Map{"platform >=": 0}
	}
	return g.Map{"platform": g.Slice{platform, 0}}
}

// findChildConfigs 递归查询指定父节点的子配置，并填充 children
func findChildConfigs(ctx context.Context, parentId dataType.TypeDataBaseId, platform int) ([]GameConfigWithChildren, error) {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return nil, err
	}
	cond := g.Map{
		"parentId": parentId,
		"isActive": 1,
	}
	for k, v := range buildPlatformCondition(platform) {
		cond[k] = v
	}

	var rows []GameConfigWithChildren
	err = base.GetDb().
		Model("game_config").
		Where(cond).
		OrderAsc("id").
		Scan(&rows)
	if err != nil {
		return nil, err
	}

	for i := range rows {
		children, err := findChildConfigs(ctx, rows[i].ParentId+rows[i].Id-rows[i].ParentId, platform)
		if err != nil {
			return nil, err
		}
		rows[i].Children = children
	}
	return rows, nil
}

// FormatConfigsFromDB 查询根(parentId=0)并递归 children，返回配置数组
func FormatConfigsFromDB(ctx context.Context, platform int) ([]GameConfigWithChildren, error) {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return nil, err
	}
	cond := g.Map{
		"parentId": 0,
		"isActive": 1,
	}
	for k, v := range buildPlatformCondition(platform) {
		cond[k] = v
	}

	var roots []GameConfigWithChildren
	err = base.GetDb().
		Model("game_config").
		Where(cond).
		OrderAsc("id").
		Scan(&roots)
	if err != nil {
		return nil, err
	}

	for i := range roots {
		children, err := findChildConfigs(ctx, roots[i].Id, platform)
		if err != nil {
			return nil, err
		}
		roots[i].Children = children
	}
	return roots, nil
}

func ClearAllConfigs() error {
	base, err := databasemanager.ManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	// 删除所有 game_config 记录
	_, err = base.GetDb().Model("game_config").Where("1=1").Delete()
	if err != nil {
		return err
	}
	logger.LoggerIns().Warn("cleared all records from table: game_config")
	return nil
}
